package com.richinfo.demo.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.richinfo.demo.dao.AreaDao;
import com.richinfo.demo.entity.Area;
import com.richinfo.demo.service.AreaService;

/**
* Created by WangXJ
* 2018-05-07 14:09
*/
@Service
public class AreaServiceImpl implements AreaService {
	
	@Autowired
	private AreaDao areaDao;

	@Override
	public List<Area> getAllAreas() {
		return areaDao.findAllAreas();
	}

	@Override
	public Area getAreaById(Integer areaId) {
		return areaDao.findAreaById(areaId);
	}

	@Transactional//默认处理RuntimeException,若想处理Exception则添加(rollbackFor=Exception.class)
	@Override
	public boolean addArea(Area area) {
		if(area.getAreaName()!=null && !"".equals(area.getAreaName())) {
			area.setCreateTime(new Date());
			area.setLastEditTime(new Date());
			try {
				int effectedNum = areaDao.insertArea(area);
				if(effectedNum > 0) {
					return true;
				}else {
					throw new RuntimeException("新增区域失败！");
				}
			} catch (Exception e) {
				throw new RuntimeException("新增区域失败！"+"错误信息:"+e.getMessage());
			}
		}else {
			throw new RuntimeException("区域名称不能为空！");
		}
	}

	@Override
	public boolean modifyArea(Area area) {
		//判断areaId不为空且大于0(因为areaId从1开始)
		if(area.getAreaId()!=null && area.getAreaId()>0) {
			area.setLastEditTime(new Date());
			try {
				int effectedNum = areaDao.updateArea(area);
				if(effectedNum > 0) {
					return true;
				}else {
					throw new RuntimeException("修改区域信息失败！");
				}
			} catch (Exception e) {
				throw new RuntimeException("修改区域信息失败！"+"错误信息:"+e.getMessage());
			}
		}else {
			throw new RuntimeException("区域Id不合法！");
		}
	}

	@Override
	public boolean deleteArea(Integer areaId) {
		if(areaId > 0) {
			try {
				int effectedNum = areaDao.deleteArea(areaId);
				if(effectedNum > 0) {
					return true;
				}else {
					throw new RuntimeException("删除区域失败！");
				}
			} catch (Exception e) {
				throw new RuntimeException("删除区域失败！"+"错误信息:"+e.getMessage());
			}
		}else {
			throw new RuntimeException("区域Id需大于0！");
		}
	}

	

}
